//
//  ZPMineFeedbackViewController.m
//  ZPIOSEducation
//
//  Created by 李伟 on 2016/12/4.
//  Copyright © 2016年 mini1. All rights reserved.
//

#import "ZPMineFeedbackViewController.h"

@interface ZPMineFeedbackViewController () <UITextFieldDelegate,UITextViewDelegate>

@property (weak, nonatomic) IBOutlet UITextView  *feedBackTV;
@property (weak, nonatomic) IBOutlet UILabel     *placeHodlerLabel;
@property (weak, nonatomic) IBOutlet UILabel     *textCountLab;
@property (weak, nonatomic) IBOutlet UITextField *mobileEmailTextF;
@property (weak, nonatomic) IBOutlet UIButton    *submitBtn;
@end

@implementation ZPMineFeedbackViewController

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesBegan:touches withEvent:event];
    [self.view endEditing:YES];
}



- (void)viewDidLoad {
    [super viewDidLoad];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]   initWithTarget:self action:@selector(dismissKeyboard)];
    [self.view addGestureRecognizer:tap];
    
    self.textCountLab.hidden = YES;
   
     [_mobileEmailTextF addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    
    // 如果是登录状态，自动填写当前用户手机号
    if ([self  checkLogin]){
        NSMutableDictionary *dataDic = [[ZPAuthStore sharedZPAuthStore] userToDic];
        if ([dataDic  objectForKey:@"mobile"] && ![[dataDic  objectForKey:@"mobile"] isEqual:[NSNull  null]] && ![[dataDic  objectForKey:@"mobile"] isEqual:@""]) {
            self.mobileEmailTextF.text = [NSString  stringWithFormat:@"%@",[dataDic  objectForKey:@"mobile"]];
        }
    }
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.title = @"意见反馈";
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"zhenpin_back"] style:UIBarButtonItemStylePlain target:self action:@selector(clickBackButtonItem)];
    self.feedBackTV.delegate = self;
    self.mobileEmailTextF.delegate = self;
}

- (void)clickBackButtonItem {
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)dismissKeyboard {
    [_feedBackTV resignFirstResponder];
    [_mobileEmailTextF resignFirstResponder];
}


// 是否登录
- (BOOL)checkLogin
{
    NSMutableDictionary *dataDic = [[ZPAuthStore sharedZPAuthStore] userToDic];
    NSString *token = [dataDic valueForKey:@"token"];
    NSString *memberId = [dataDic valueForKey:@"memberId"];
    if ([token isEqual:[NSNull null]] ||[token length] <=0 || [memberId isEqual:[NSNull null]] ||[memberId length] <=0 ) {
        return NO;
    }else {
        return YES;
    }
}



#pragma mark - <textField DidChange>
- (void)textFieldDidChange:(UITextField *)sender
{
    NSInteger textLength = [sender.text isContainsEmoji:sender.text];
    if (textLength != 0) {
        sender.text = [sender.text substringToIndex:sender.text.length - textLength];
        
    }else{
        NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"[^\\u0020-\\u007E\\u00A0-\\u00BE\\u2E80-\\uA4CF\\uF900-\\uFAFF\\uFE30-\\uFE4F\\uFF00-\\uFFEF\\u0080-\\u009F\\u2000-\\u201f\r\n]" options:NSRegularExpressionCaseInsensitive error:nil];
        NSUInteger numberOfMatches = [regex numberOfMatchesInString:sender.text options:NSMatchingWithTransparentBounds range:NSMakeRange(0,[sender.text length])];
        if (numberOfMatches > 0) {
            NSString * newString;
            if ([sender.text hasSuffix:@"➕"] || [sender.text hasSuffix:@"➖"]|| [sender.text hasSuffix:@"➗"]) {
                newString = [sender.text substringToIndex:sender.text.length - 1];
            }else{
                newString = [sender.text substringToIndex:sender.text.length - 2];
            }
            
            sender.text = newString;
        }
    }
//    [self changeSubmitBtnColor];
}



- (void)textViewDidChange:(UITextView *)sender
{
    NSInteger textLength = [sender.text isContainsEmoji:sender.text];
    
    if (textLength != 0) {
        sender.text = [sender.text substringToIndex:sender.text.length - textLength];
        
    }else{
        NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"[^\\u0020-\\u007E\\u00A0-\\u00BE\\u2E80-\\uA4CF\\uF900-\\uFAFF\\uFE30-\\uFE4F\\uFF00-\\uFFEF\\u0080-\\u009F\\u2000-\\u201f\r\n]" options:NSRegularExpressionCaseInsensitive error:nil];
        NSUInteger numberOfMatches = [regex numberOfMatchesInString:sender.text options:NSMatchingWithTransparentBounds range:NSMakeRange(0,[sender.text length])];
        if (numberOfMatches > 0) {
            NSString * newString;
            if ([sender.text hasSuffix:@"➕"] || [sender.text hasSuffix:@"➖"]|| [sender.text hasSuffix:@"➗"]) {
                newString = [sender.text substringToIndex:sender.text.length - 1];
            }else{
                newString = [sender.text substringToIndex:sender.text.length - 2];
            }
            
            sender.text = newString;
        }
    }
    
    NSInteger number = [sender.text length];
    
    if (number > 300) {
        sender.text = [sender.text substringToIndex:300];
        return;
    }
    if (number > 249) {
        self.textCountLab.hidden = NO;
        self.textCountLab.text = [NSString  stringWithFormat:@"%ld",MAX(0, 300-number)];
    }else {
        self.textCountLab.hidden = YES;
    }
    [self  changeSubmitBtnColor];
}



- (void)changeSubmitBtnColor
{
    if (self.feedBackTV.text.length != 0) {
        [self.submitBtn  setBackgroundColor:zMainColor];
    }else {
        [self.submitBtn  setBackgroundColor:zFreeColor(204, 204, 204, 1)];
    }
}



- (void)textViewDidBeginEditing:(UITextView *)textView
{
    _placeHodlerLabel.hidden = YES;
}



- (IBAction)submitBtnClick:(id)sender
{
    NSString *content = _feedBackTV.text;
    if ([content length] == 0||[content isEqual:[NSNull null]]) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"请正确填写反馈内容" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alert show];
        return;
    }
     NSDictionary *params;
    if (![[ZPAuthEngine sharedZPAuthEngine] isValid]) {
        params = @{
                   @"email": NU(_mobileEmailTextF.text),
                   @"content":content,
                   @"v":@"2.0"
                   };
    } else {
        
        NSString  *userNameStr = [[[ZPAuthStore sharedZPAuthStore] userToDic] objectForKey:@"userName"];
        NSString  *newContentStr = [NSString  stringWithFormat:@"平台:石头培优app(ios) 版本:%@ 用户名:%@ 用户id:%@ 反馈内容:%@",[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"],userNameStr,[[[ZPAuthStore sharedZPAuthStore] userToDic] objectForKey:@"memberId"],content];
        params = @{@"memberid": [[[ZPAuthStore sharedZPAuthStore] userToDic] objectForKey:@"memberId"],
                   @"access_token": [[[ZPAuthStore sharedZPAuthStore] userToDic]valueForKey:@"token"],
                   @"email": NU(_mobileEmailTextF.text),
                   @"content":newContentStr,
                   @"v":@"2.0"
                   };
    }
    MBProgressHUD *HUD  = [MBProgressHUD showHUDAddedTo:self.view.window animated:YES];
    HUD.label.text = @"发送反馈";
    
    [self performSelector:@selector(backPreview) withObject:nil afterDelay:1.0f];
    
/*    [[ZPNetworking sharedZPNetworking] POST:@"" parameters:params progress:^(NSProgress * _Nullable progress) {
        
    } success:^(id  _Nonnull responseObject) {
        NSInteger  code = [[responseObject  objectForKey:@"code"] integerValue];
        [MBProgressHUD hideHUDForView:self.view.window animated:YES];
        
        if (code == 200) {
            if ([[[responseObject objectForKey:@"result"] objectForKey:@"isOk"] boolValue]) {
                [ZPPromptView showMessage:@"发送成功!"];
                [self.navigationController popViewControllerAnimated:YES];
            } else {
                [ZPPromptView showMessage:[responseObject objectForKey:@"codeMsg"]];
            }
        } else {
            [ZPPromptView showMessage:[responseObject objectForKey:@"codeMsg"]];
        }
    } failure:^(NSError * _Nonnull error) {
        [MBProgressHUD hideHUDForView:self.view.window animated:YES];
        [ZPPromptView showMessage:@"请检查您的网络设置哦"];
    }];
 */
}

- (void)backPreview
{
    [ZPPromptView showMessage:@"意见反馈成功!"];
    [MBProgressHUD hideHUDForView:self.view.window animated:YES];
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end
